package com.peanut.baby.mvp.record;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.peanut.baby.R;
import com.peanut.baby.comm.BaseDialog;
import com.peanut.baby.model.Photo;
import com.peanut.baby.model.UploadConf;
import com.peanut.baby.mvp.AddPhotoGridAdapter;
import com.peanut.baby.mvp.BaseMvpActivity;
import com.peanut.baby.util.AppUtil;
import com.peanut.baby.widget.UnScrollGridView;
import com.peanut.devlibrary.RequestResult;
import com.peanut.devlibrary.picker.ImageConfig;
import com.peanut.devlibrary.picker.PhotoPickerActivity;
import com.peanut.devlibrary.picker.PhotoPreviewActivity;
import com.peanut.devlibrary.util.StringUtil;
import com.peanut.devlibrary.util.TimeUtil;
import com.peanut.devlibrary.widget.TitleLayout;
import com.tencent.mars.xlog.Log;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by anonymouslystudio on 2017/8/9.
 */

public class RecordEditActivity extends BaseMvpActivity implements TitleLayout.OnTitleClickListener,
        AddPhotoGridAdapter.OnPhotoDeleteListener,
        AdapterView.OnItemClickListener,
        RecordEditContract.View,
        View.OnClickListener {
    private static final String TAG = RecordEditActivity.class.getSimpleName();

    public static final int TYPE_ZHENLIAO = 0;
    public static final int TYPE_TIAOLI = 1;

    private static final int MAX_PHOTO_NUM = 10;
    @BindView(R.id.title)
    TitleLayout title;

    @BindView(R.id.submit)
    TextView submit;
    @BindView(R.id.record_time)
    TextView recordTime;
    @BindView(R.id.record_type_value)
    TextView recordTypeValue;
    @BindView(R.id.record_type)
    LinearLayout recordType;
    @BindView(R.id.record_edit)
    EditText recordEdit;
    private AddPhotoGridAdapter adapter;
    private List<Photo> photos;


    @BindView(R.id.record_photo_grid)
    UnScrollGridView photoGrid;

    private RecordEditPresenter presenter;

    private List<UploadConf> successConfigs;

    private int type = TYPE_ZHENLIAO;

    /**
     * @param ctx
     */
    public static void start(Context ctx, int type) {
        ctx.startActivity(new Intent(ctx, RecordEditActivity.class).putExtra("type", type));
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record_edit);
        ButterKnife.bind(this);
        type = getIntent().getIntExtra("type", TYPE_ZHENLIAO);
        presenter = new RecordEditPresenter(this,this);
        initialViews();
    }

    private void initialViews() {
        title.setTitle(type == TYPE_ZHENLIAO ? "诊疗记录" : "调理记录");
        title.setOnTitleClickedListener(this);

        recordTime.setText("记录时间: "+ TimeUtil.getCurrentDate());

        submit.setOnClickListener(this);
        recordType.setOnClickListener(this);

        photos = new ArrayList<>();

        Photo addFlag = new Photo();
        addFlag.url = Photo.FLAG_ADD;
        photos.add(addFlag);

        adapter = new AddPhotoGridAdapter(this, photos);
        adapter.setOnPhotoDeleteListener(this);
        photoGrid.setAdapter(adapter);
        photoGrid.setOnItemClickListener(this);

    }

    @Override
    public void onTitleBackClicked() {
        finish();
    }

    @Override
    public void onTitleRightClicked() {

    }

    @Override
    public void onTitleClicked() {

    }

    @Override
    public void onPhotoDelete(int position) {
        photos.remove(position);

        if ((photos.size() == (MAX_PHOTO_NUM - 1))
                && (!photos.get(photos.size() - 1).url.equals(Photo.FLAG_ADD))) {
            Photo addFlag = new Photo();
            addFlag.url = Photo.FLAG_ADD;
            photos.add(addFlag);
        }

        adapter.notifyDataSetChanged();
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Photo bean = (Photo) adapter.getItem(position);
        if (bean.url.equals(Photo.FLAG_ADD)) {
            presenter.checkPermissionBeforeSelectPhoto(RecordEditActivity.this);
        } else {
            Log.d(TAG, "on preview photos " + position);
            PhotoPreviewActivity.start(RecordEditActivity.this, getPreviewList(), position);
        }
    }

    /**
     * get list of images for preview
     *
     * @return
     */
    private ArrayList<String> getPreviewList() {
        ArrayList<String> previews = new ArrayList<>();
        for (int i = 0; i < photos.size(); i++) {
            if (!TextUtils.isEmpty(photos.get(i).url)) {
                if (!photos.get(i).url.equals(Photo.FLAG_ADD)) {
                    previews.add(photos.get(i).url);
                }
            } else {
                if (!TextUtils.isEmpty(photos.get(i).path)) {
                    previews.add(photos.get(i).path);
                }
            }
        }
        Log.d(TAG, "getPreviewList photos " + (previews == null ? "null" : " size " + previews.size()));
        return previews;
    }

    @Override
    public void onPermissionGranted(List<String> grantPermissions) {
        int realPhotoSize = photos.size();
        if (photos.get(photos.size() - 1).url.equals(Photo.FLAG_ADD)) {
            realPhotoSize = realPhotoSize - 1;
        }
        PhotoPickerActivity.startForResult(RecordEditActivity.this, MAX_PHOTO_NUM - realPhotoSize, true, PhotoPickerActivity.MODE_MULTI, new ImageConfig());
    }

    @Override
    public void onPermissionDenied(List<String> grantPermissions) {

    }

    @Override
    public void onPictureUploadFinished(List<UploadConf> configs) {
        dismissProgressDialog();

        final List<UploadConf> failedList = new ArrayList<>();
        for(int i=0;i<configs.size();i++){
            if(!configs.get(i).uploadSuccess){
                failedList.add(configs.get(i));
            }else{
                successConfigs.add(configs.get(i));
            }
        }

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(failedList != null && !failedList.isEmpty()){
                    new BaseDialog().showConfirmCancelAlert(RecordEditActivity.this, failedList.size() + "张图片上传失败，是否重新上传?",
                            "重传", "取消", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    showProgressDialog("正在重传...",false);
                                    presenter.reUpload(failedList);
                                }
                            }, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    submitAfterPhotoUploaded();
                                }
                            });
                }else{
                    submitAfterPhotoUploaded();
                }
            }
        });

    }


    @Override
    public void onSubmitRecordSuccess() {
        dismissProgressDialog();
        showToast("提交成功");
        finish();
    }


    @Override
    public void onRequestFailed(String reason) {
        dismissProgressDialog();
        showToast("提交失败 "+reason);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case RequestResult.REQUEST_CODE_PHOTOS:
                ArrayList<String> _photos = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                onPickPhotoResult(_photos);
                break;
        }
    }

    private void onPickPhotoResult(ArrayList<String> result) {
        Log.d(TAG, "onPickPhotoResult _photos.size: " + (result == null ? "null" : "size:" + result.size()));
        if (result != null && !result.isEmpty()) {
            if (photos.get(photos.size() - 1).url.equals(Photo.FLAG_ADD)) {
                photos.remove(photos.size() - 1);
            }
            for (int i = 0; i < result.size(); i++) {
                Photo photo = new Photo();
                photo.path = result.get(i);
                photo.url = "";
                photos.add(photo);
            }

            // if size > MAX_PHOTO_SIZE,
            if (photos.size() > MAX_PHOTO_NUM) {
                photos = photos.subList(0, MAX_PHOTO_NUM);
            }
            //if size < MAX_PHOTO_SIZE, ADD_FLAG
            if (photos.size() < MAX_PHOTO_NUM) {
                Photo addFlag = new Photo();
                addFlag.url = Photo.FLAG_ADD;
                photos.add(addFlag);
            }
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.submit:
                checkParamsBeforeSubmit();
                break;
            case R.id.record_type:
                new BaseDialog().showListDialog(RecordEditActivity.this,
                        "请选择类型",
                        type == TYPE_ZHENLIAO ? AppUtil.getZhenliaoTypeList() : AppUtil.getTiaoliTypeList(),
                        new BaseDialog.OnListItemSelectedListener() {
                            @Override
                            public void onListItemSelected(String value) {
                                recordTypeValue.setText(value);
                            }
                        });
                break;
        }
    }

    private void checkParamsBeforeSubmit(){
        String type = recordTypeValue.getText().toString().trim();
        if(StringUtil.isNullOrEmpty(type)){
            showToast("请选择记录类型");
            return;
        }
        String content = recordEdit.getText().toString().trim();
        if(StringUtil.isNullOrEmpty(content)){
            showToast("请输入记录内容");
            return;
        }
        if(photos != null && !photos.isEmpty()){
            showProgressDialog("图片上传中...",false);
            if(successConfigs == null){
                successConfigs = new ArrayList<>();
            }
            successConfigs.clear();
            presenter.compressAndUploadPicture(getPreviewList());
        }else{
            submitRecord(type,content,"");
        }
    }

    /**
     *
     * @param _type
     * @param content
     * @param images
     */
    private void submitRecord(String _type,String content,String images){
        showProgressDialog("正在提交...",false);
        presenter.submitRecord(type,_type,content,images);
    }

    private void submitAfterPhotoUploaded(){
        Log.d(TAG,"submitAfterPhotoUploaded");
        String typeString = recordTypeValue.getText().toString().trim();
        String content = recordEdit.getText().toString().trim();
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<successConfigs.size();i++){
            sb.append(successConfigs.get(i).getResultFullUrl());
            if(i != successConfigs.size() - 1){
                sb.append(",");
            }
        }
        submitRecord(typeString,content,sb.toString());
    }
}